//
//  LBXLoggerRealServer.m
//  WebServerTools
//
//  Created by 夏利兵 on 2020/9/23.
//  Copyright © 2020 com.lbx. All rights reserved.
//

#import "LBXLoggerRealServer.h"
#import "HTTPServer.h"
#import "WebSocketConnection.h"
#import "WebSocket.h"

#import <ifaddrs.h>
#import <arpa/inet.h>


@interface LBXLoggerRealServer()
@property (nonatomic, strong) HTTPServer *server;

@end

@implementation LBXLoggerRealServer

+ (instancetype)sharedManager
{
    static LBXLoggerRealServer* _sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[LBXLoggerRealServer alloc] init];
        _sharedInstance.port = 61234;
    });
    
    return _sharedInstance;
}

- (BOOL)start
{
    if (_server) {
        return YES;
    }
    
    
    self.server = [[HTTPServer alloc] init];
    [self.server setType:@"_http._tcp."];
    [self.server setPort:self.port];
    //    [httpServer setConnectionClass:ALHTTPConnection.class];
    [self.server setConnectionClass:WebSocketConnection.class];
    
    // Serve files from our embedded Web folder
    NSString *webPath = [self requestLogWebPath];
    [self.server setDocumentRoot:webPath];
    // Start the server (and check for problems)
    NSError *error = nil;
    BOOL ret = [self.server start:&error];
    
    if (error) {
        NSLog(@"LBXLoggerRealServer start error:%@",error);
        self.errMsg = [NSString stringWithFormat:@"%@",error];
        self.server = nil;
    }
    
    if (ret) {
        self.published = YES;
    }
    
    return ret;
}

- (void)stop
{
    if (_server) {
        [_server stop];
        self.server = nil;
        self.published = NO;
    }
}


+ (void)log:(NSString *)format, ... {
    
    va_list args;
    
    if (format) {
        va_start(args, format);
        
        NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
        NSString *logString = [self formatForMessage:message];
        
        va_end(args);
        
        [[LBXLoggerRealServer sharedManager]sendMessage:logString];
    }
    
}

+ (void)logWithFile:(NSString*)fileName format:(NSString *)format, ... {
    
   
    
    va_list args;
    
    if (format) {
        va_start(args, format);
        
        NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
        NSString *logString = [self formatForMessage:message];
        
        va_end(args);
        
        [[LBXLoggerRealServer sharedManager]sendMessage:logString];
    }
    
    {
//        NSString *fileName = [NSString stringWithUTF8String:__FILE__];
//
//        fileName = [fileName lastPathComponent];
//
//        NSString *func = [NSString stringWithUTF8String:__func__];
//        fileName = [NSString stringWithFormat:@"%@-%@",fileName,func];
    }

//    [LBXLoggerRealServer logWithFile:fileName format:(fmt) , ## __VA_ARGS__];
    
}

+ (NSString *)formatForMessage:(NSString *)format {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
//    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss:SSS"];
    [dateFormatter setDateFormat:@"HH:mm:ss:SSS"];

    NSString *dateAndTime = [dateFormatter stringFromDate:(NSDate.date)];
    
    NSString *file = [NSString stringWithUTF8String:__FILE__];
    return [NSString stringWithFormat:@"%@ [%@]- %@", dateAndTime,file.lastPathComponent, format];
}

- (BOOL)sendMessage:(NSString *)logMessage
{
    if (!_server) {
        return NO;
    }
    
    NSArray *arr = [_server valueForKey:@"webSockets"];
    if (!arr || arr.count <= 0) {
        return NO;
    }
    
    for (WebSocket *st in arr) {
        
        [st sendMessage:logMessage];
    }
    
   return YES;
}

- (NSString *)requestLogWebPath
{
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"LogServerResource" ofType:@"bundle"];
    
    filePath  = [filePath stringByAppendingPathComponent:@"requestLog"];
    
    return filePath;
}


- (NSString*)visitUrl
{
    NSString *url = [NSString stringWithFormat:@"http://%@:%d",[self deviceIPAdress],self.port];
    return url;
}

- (NSString *)deviceIPAdress {
    
    NSString *address = @"";
    
    struct ifaddrs *interfaces = NULL;
    
    struct ifaddrs *temp_addr = NULL;
    
    int success = 0;
    
    success = getifaddrs(&interfaces);
    
    if (success == 0) { // 0 表示获取成功
        
        temp_addr = interfaces;
        
        while (temp_addr != NULL) {
            
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                
                // Check if interface is en0 which is the wifi connection on the iPhone
//                NSLog(@"%@",[NSString stringWithUTF8String:temp_addr->ifa_name]);
//                 NSString* str = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
//                NSLog(@"%@",str);
                
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"] || [[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en1"] ) {
                    
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    
                }
                
            }
            
            temp_addr = temp_addr->ifa_next;
            
        }
        
    }
    
    freeifaddrs(interfaces);
    
    return address;
    
}

@end
